package cn.tedu._03vehicle.base.exception;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(IllegalArgumentException.class)
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex) {
        String date = ex.getMessage();
        log.error("doHandleIllegalArgumentException:" + date);
        return JsonResult.fail(date);
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public JsonResult doHandleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex) {
        String date = ex.getMessage();
        log.error("doHandleMaxUploadSizeExceededException:" + date);
        return new JsonResult(StatusCode.MAX_UPLOAD_SIZE_ERROR,date);
    }

    @ExceptionHandler(RuntimeException.class)
    public JsonResult doHandleRuntimeException(RuntimeException ex) {
        String data = ex.getMessage();
        log.error("doHandleRuntimeException:" + data);
        return JsonResult.fail(data);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        String data = ex.getFieldError().getDefaultMessage();
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex) {
        String data = ex.getMessage().split(":")[1].trim();
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }
    @ExceptionHandler(Throwable.class)
    public JsonResult doHandleThrowable(Throwable ex){
        String data = ex.getMessage();
        log.error("doHandleThrowable:" + data);
        return new JsonResult(StatusCode.THROWABLE_ERROR, data);
    }
}
